package com.tzstcl.framework.shiro;


import com.tzstcl.framework.config.AppConfig;
import com.tzstcl.framework.constants.AppConstants;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证码过滤器
 *
 * @author haocj
 */
public class CaptchaValidateFilter extends AccessControlFilter {
    @Autowired
    private AppConfig appConfig;
    /**
     * 是否开启验证码
     */
    @Value("${project.captchaEnabled:true}")
    private boolean captchaEnabled ;

    /**
     * 验证码类型
     */
    @Value("${project.captchaType:math}")
    private String captchaType ;

    public void setCaptchaEnabled(boolean captchaEnabled) {
        this.captchaEnabled = captchaEnabled;
    }

    public void setCaptchaType(String captchaType) {
        this.captchaType = captchaType;
    }

    @Override
    public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        request.setAttribute(AppConstants.CURRENT_ENABLED, captchaEnabled);
        request.setAttribute(AppConstants.CURRENT_TYPE, captchaType);
        return super.onPreHandle(request, response, mappedValue);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        if (appConfig.getLoginPath().equals(httpServletRequest.getServletPath().toLowerCase())) {
            return validateResponse(httpServletRequest, httpServletResponse, httpServletRequest.getParameter(AppConstants.CURRENT_VALIDATECODE));
        }
        return true;
    }

    public boolean validateResponse(HttpServletRequest request, HttpServletResponse response, String validateCode) throws IOException {
        Object obj = request.getSession().getAttribute(AppConstants.KAPTCHA_SESSION_KEY);
        String code = String.valueOf(obj != null ? obj : "");
        if (StringUtils.isEmpty(validateCode) || !validateCode.equalsIgnoreCase(code)) {
            return false;
        }
        System.out.println("服务器验证码验证："+code+",  网页验证码验证："+validateCode+"  验证通过");
        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        request.setAttribute(AppConstants.CURRENT_CAPTCHA, AppConstants.CAPTCHA_ERROR);
        return false;
    }

}
